package com.wyx.bbs;

import com.alibaba.fastjson.JSON;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;


import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;

public class UploadResource {

/**
 * 图片路径
 */
private final static String IMG_PATH = "XXX";

/**
 * oss 文件路径
 */
private static final String VIEW_PATH = "XXX";

/**
 * oss ENDPOINT
 */
private static final String ENDPOINT = "XXX";

/**
 * oss ACCESS_KEY_ID
 */
private static final String ACCESS_KEY_ID = "XXX";

/**
 * oss ACCESS_KEY_SECRET
 */
private static final String ACCESS_KEY_SECRET = "XXX";

/**
 * oss BUCKET_NAME
 */
private static final String BUCKET_NAME = "XXX";

/**
 * 创建oss client
 */
private static OSS OSS_CLIENT = new OSSClientBuilder().build(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);

private static List<String> IMAGE_TYPE = new ArrayList<String>();

static {
    IMAGE_TYPE.add(".jpg");
    IMAGE_TYPE.add(".jpeg");
    IMAGE_TYPE.add(".png");
}

/**
 * 上传图片
 *
 * @date 2020/9/1 10:30
 */
public static void uploadImg(String path) {

    // path为空,则读取F:\image 目录下的图片
    if (path == null || "".equals(path.trim())) {
        path = "C:\\Users\\19849\\Desktop\\fruits";
    }

    System.out.println("path:"+path);

    // 上传到目录结构有两层, 因为我的需求上传图片以图集为单位,所以path路径下每个文件夹为一个图集,文件夹是对应图集的图片
    File file = new File(path);
    File[] fs1 = file.listFiles();

    // 保存每个图集的url
    List<Map<Integer, String>> resourceList = new ArrayList<Map<Integer, String>>();
    Map<Integer, String> resourceMap;
    String type;
    UUID uuid;
    String randomStr;
    String fileName;
    String uploadPath;

    Long startTime = System.currentTimeMillis();
    System.out.println(" ================== >>> upload start ..."+fs1);

    int count = 1;
    float total = fs1.length;

    try {
        // 遍历该路径下的文件夹
        for (File f1 : fs1) {

            // 该文件不是目录则跳过
            if (!f1.isDirectory()) {
                continue;
            }

            resourceMap = new HashMap<Integer, String>();
            int i = 1;
            // 遍历改文件夹中的文件
            for (File f2 : f1.listFiles()) {

                // 到第二层文件夹下，则要判断file是否为文件，如果不是则跳过
                if (f2.isDirectory()) {
                    continue;
                }

                // 获取素材类型
                type = f2.getName().substring(f2.getName().lastIndexOf("."));

                // 判断素材类型不是图片则跳过该循环
                if (!IMAGE_TYPE.contains(type)) {
                    continue;
                }

                // 生成素材名称
                uuid = UUID.randomUUID();
                randomStr = uuid.toString().substring(0, 16);
                fileName = getCurrentDay() + "_" + randomStr + type;
                uploadPath = IMG_PATH + "/" + getCurrentDay() + "/" + fileName;

                // 上传至oss
                OSS_CLIENT.putObject(BUCKET_NAME, uploadPath, f2);

                // 生成oss 访问的url
                String imgUrl = VIEW_PATH + uploadPath;
                // 暂存的集合中
                resourceMap.put(i++, imgUrl);
            }
            resourceList.add(resourceMap);
            System.out.println(" ================== >>>  " + (int) (Float.valueOf(count) / total * 100) + " %");
            count++;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    //TODO 当上传成功以后可以将 resourceList 里的数据持久化到数据库,可以连数据库也可以用远程调用接口


    System.out.println(JSON.toJSON(resourceList).toString());
    System.out.println(" ================== >>> upload end !!!  run time: " + ((System.currentTimeMillis() - startTime) / 1000) + " s");
}

public static String getCurrentDay() {
    return new SimpleDateFormat("yyyyMMdd").format(new Date());
}

public static void main(String[] args) {
    String filePath = null;
    if (args.length > 0) {
        filePath = args[0];
    }
    uploadImg(filePath);
}
}